package edu.ccut.saturn.manager.dict.core;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IDataDictTypeInfo;
import edu.ccut.saturn.component.IDictItemInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnDictionaryManager;

public class AddDictParam extends DefaultComponent {

	private static final String QUERY_SQL = "SELECT * FROM saturn_dict where type = ? and code = ?";

	private static final String PARAM_INSERT_SQL = "INSERT INTO saturn_dict (type,code,value,pinyin,parent_code) VALUES(?,?,?,?,?)";

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		String type = (String) parameterContext.getParameterValue(0);
		String code = (String) parameterContext.getParameterValue(1);
		String value = (String) parameterContext.getParameterValue(2);
		String pinyin = (String) parameterContext.getParameterValue(3);
		String parentCode = (String) parameterContext.getParameterValue(4);

		if (parentCode == null) {
			parentCode = "";
		}

		String addSucc = "false";

		PreparedStatement statement = null;
		ResultSet rs = null;

		try {
			statement = parameterContext.getConnection().prepareStatement(
					QUERY_SQL);

			statement.setString(1, type);
			statement.setString(2, code);

			rs = statement.executeQuery();

			if (!rs.next()) {

				statement = parameterContext.getConnection().prepareStatement(
						PARAM_INSERT_SQL);

				statement.setString(1, type);
				statement.setString(2, code);
				statement.setString(3, value);
				statement.setString(4, pinyin);
				statement.setString(5, parentCode);

				int result = statement.executeUpdate();

				if (result == 1) {
					addSucc = "true";
				}
			}
		} catch (Exception e) {
			logger.error("found exception when execute Component Node "
					+ this.getComponentFullKey(), e);
		} finally {
			if (rs != null) {
				rs.close();
			}
			if (statement != null) {
				statement.close();
			}
		}

		if ("true".equals(addSucc)) {
			IDataDictTypeInfo dataDictTypeInfo = SaturnDictionaryManager
					.getInstance().getDataDictTypeInfo(type);

			List<IDictItemInfo> dictItemList = dataDictTypeInfo.getItems();

			if (dictItemList == null) {
				dictItemList = new ArrayList<IDictItemInfo>();
			}

			IDictItemInfo dictItem = SaturnDictionaryManager.getInstance()
					.CreateDictItemInfo();

			dictItem.setType(type);
			dictItem.setCode(code);
			dictItem.setValue(value);
			dictItem.setPinyin(pinyin);
			dictItem.setParentCode(parentCode);
			dictItemList.add(dictItem);

			SaturnDictionaryManager.getInstance().getDataDictTypeInfo(type)
					.setItems(dictItemList);
		}

		parameterContext.setParameter(5, addSucc);
	}
}
